<?php

namespace App\Console\Commands\OpenShop\Renew;

use App\Enums\OpenShop\InvestmentPromotion\ContractStatusEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Enums\Workflow\WorkflowEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\Shop\OpenShopHandleExpireShopHistoryModel;
use App\Models\OpenShop\Shop\OpenShopHandleExpireShopMainModel;
use App\Models\Renew\RenewOrder\RenewDeferOperateHistoryModel;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Common\SendVoiceService;
use App\Service\Cruise\Shop\CruiseShopService;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\Workflow\WorkflowOrderService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;
use Kuafu\Nsq\NsqPublisher;

class BatchDeferExpireOrderCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'renew:batchDeferExpireOrder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '续签单：批处理延期已过期订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        OpenShopMainProcessModel::query()
                                ->where("childLocationOrder", 0)
                                ->where("nowStepStatus", MissionTemplateEnum::STEP_STATUS_999)
                                ->where("shopId", ">", 0)
                                ->with([
                                    "signOrderRel",
                                    "userIdentityCardRel",
                                    "userContractsRel",
                                    "userBaseInfoRel",
                                    "userExperienceRel",
                                    "checkAcceptRel"
                                ])
                                ->chunkById(100,
                                    function (Collection $collection) {
                                        //todo 遍历合同根据合同有效期判断是否创建续签工单
                                        $collection->each(function (OpenShopMainProcessModel $mainProcessModel) {
                                            try {
                                                if ($mainProcessModel->userContractsRel->isNotEmpty()) {
                                                    if ($mainProcessModel->userContractsRel->count() == 1) {
                                                        //合同只有一条  取当前一条
                                                        $userContractModel = $mainProcessModel->userContractRel;
                                                    } else {
                                                        //存在多条 取出开店或者续签合同完成的合同
                                                        $userContractModel = $mainProcessModel->userContractRel
                                                            ->where("detailStatus", ContractStatusEnum::COMPLETE)
                                                            ->whereIn("contractType",
                                                                OpenShopUserContractModel::OPEN_SHOP_CONTRACT_GROUP)
                                                            ->orderBy("id", "desc")->first();
                                                    }

                                                    //已过期 && 合同已签署 && 主流程信息存在 && 为主订单
                                                    if ($userContractModel && $userContractModel->endTime < time()) {
                                                        $this->getOutput()->info($userContractModel->orderNo);
                                                        $endTime     = strtotime("+30 day", time());
                                                        $endTimeDate = date("Y-m-d", $endTime);
                                                        RenewDeferOperateHistoryModel::query()->insert([
                                                            "shopId"       => $userContractModel->mainProcessRel->shopId,
                                                            "shopCode"     => $userContractModel->signOrderRel->shopCode,
                                                            "orderNo"      => $userContractModel->orderNo,
                                                            "lastEndTime"  => $userContractModel->endTime,
                                                            "endTime"      => $endTime,
                                                            "createdAt"    => time(),
                                                            "createdByUid" => 0
                                                        ]);

                                                        (new NsqPublisher(config('nsq.default.address')))
                                                            ->pub('tiger.openShop.shopStatus.switch', [
                                                                'nsqEventTime'  => time(),
                                                                'shopId'        => $userContractModel->mainProcessRel->shopId,
                                                                'switch'        => 1, // 门店禁用关闭为 0
                                                                'operatorId'    => 0,
                                                                'operatorName'  => "系统",
                                                                'reason'        => "续签订货延期至【 {$endTimeDate} 】",
                                                                'operationTime' => time()
                                                            ]);
                                                    }
                                                }
                                            } catch (Exception $exception) {
                                                logException("行执行报错", $exception, $mainProcessModel->toArray(), true,
                                                    true);
                                            }
                                        });
                                    });
        return 0;
    }
}
